from django.contrib import auth
from django.contrib.auth.models import User
from django.shortcuts import render, redirect

from worksite import form


# 登入
def login(request):
    if request.method == 'POST':
        # 获取用户、密码
        username = request.POST.get("username")
        password = request.POST.get("password")
        # print(username,password)
        # 获取的表单数据与数据库进行比较
        user = auth.authenticate(username=username, password=password)
        if user:

            # 设置session
            request.session['username'] = username
            # 比较成功，跳转index
            # print(user)
            return redirect("/index.html", )
        else:
            # 比较失败，重新登入
            return redirect("/login.html", )

    # return render(req, 'login.html', context)
    return render(request, "login/login.html")


# 用户注册
def register(request):
    # if request.met
    if request.method == "POST":
        # 从POST中获得数据
        form_obj = form.RegForm(request.POST)
        # 校验form组件数据
        if form_obj.is_valid():
            # 删除多余的验证密码字段
            form_obj.cleaned_data.pop("re_password")
            # print(form_obj.cleaned_data)
            # 添加用户
            User.objects.create_user(**form_obj.cleaned_data)
            # User.save()
            return redirect("/index.html", )
        else:
            # print(form_obj.errors)

            return render(request, "login/reg.html", {"form_obj": form_obj})

    form_obj = form.RegForm()
    return render(request, "login/reg.html", {"form_obj": form_obj})


def logout(request):
    request.session.flush()
    return redirect("/index.html")
